<script setup lang="ts">
import { loginMobile, loginQQ } from '@/apis/user';
import { rulesCode, rulesMobile } from '@/utils/rules';
import { onMounted, ref } from 'vue';

const openId = ref('')
const isNeedBind = ref(false)
const mobile = ref('')
const code = ref('')
//发送验证码
import { useMobileCode } from '@/composable/useMobileCode'
import { showSuccessToast } from 'vant';
import router from '@/router';
import type { UserType } from '@/types/user';
const { onSend, time, formTel } = useMobileCode(mobile, 'bindMobile')
import { useUserStore } from '@/stores/modules/user'
const store = useUserStore()
//第三方登录
onMounted(() => {
  if (QC.Login.check()) {
    QC.Login.getMe((id) => {
      openId.value = id
      loginQQ(openId.value).then((res) => {
        //登录成功
        loginBing(res.data)
      }).catch(() => {
        //登录失败
        isNeedBind.value = true
      })
    })
  }
})

const loginBing = (data: UserType) => {
  store.setStore(data)
  router.replace('/user')
  showSuccessToast('登录成功')
}
//手机号码绑定登录
const onSubmit = async () => {
  const res = await loginMobile({ mobile: mobile.value, code: code.value, openId: openId.value })
  //登录成功，提示用户，跳转用户页面,把用户信息存储到本地存储里面
  loginBing(res.data)
}

</script>
<template>
  <div class="login-page" v-if="isNeedBind">
    <cp-nav-bar></cp-nav-bar>
    <div class="login-head">
      <h3>手机绑定</h3>
    </div>
    <van-form autocomplete="off" ref="formTel" @submit="onSubmit">
      <van-field name="mobile" placeholder="请输入手机号" v-model="mobile" :rules="rulesMobile"></van-field>
      <van-field name="code" placeholder="请输入验证码" v-model="code" :rules="rulesCode">
        <template #button>
          <span class="btn-send" @click="onSend" :class="{ active: time > 0 }">{{ time > 0 ? `${time}秒后发送验证码` : "发送验证码"
            }}</span>
        </template>
      </van-field>
      <div class="cp-cell">
        <van-button block round type="primary" native-type="submit"> 立即绑定 </van-button>
      </div>
    </van-form>
  </div>
</template>

<style scoped>
@import '@/styles/login.scss';
</style>